package com.guan.serviceorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guan.commonutils.JwtUtils;
import com.guan.commonutils.R;
import com.guan.serviceorder.entity.Order;
import com.guan.serviceorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2023-04-24
 */
@RestController
@RequestMapping("/serviceorder/order/*")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;


    /**
     * @date: 2023/4/24 16:43
     * @author: 管奇安
     * @description: 根据课程id生成订单
     * @param:
     * [courseId]
     * request 登录之后，request中保存了用户信息 获取用户id
     * @return: com.guan.commonutils.R
     **/
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){
        //创建订单 返回订单号
        String orderNo = orderService.createOrders(courseId,JwtUtils.getMemberIdByJwtToken(request));

        return R.ok().data("orderId",orderNo);
    }


    /**
     * @date: 2023/4/24 17:31
     * @author: 管奇安
     * @description: 根据订单号查询订单信息
     * @param: [orderId]
     * @return: com.guan.commonutils.R
     **/
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo (@PathVariable String orderId){

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);

        return R.ok().data("order",order);
    }

    /**
     * @date: 2023/4/25 15:18
     * @author: 管奇安
     * @description: 根据课程 id 用户 id 查询订单状态
     * @param: [courseId, memberId]
     * @return: boolean
     **/
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId, @PathVariable String memberId){
        boolean isBuy = false;
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if (count > 0){
            isBuy = true;
        }
        return isBuy;
    }

}

